package org.finesys.common.log.trace.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.finesys.common.log.trace.util.TraceIdUtil;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import static net.logstash.logback.marker.Markers.append;
import static org.finesys.common.log.constants.TraceConstants.*;

@Slf4j
public abstract class AbstractInterceptor {

    public String getTraceId() {
        return MDC.get(TRACE_ID);
    }

    public String getSpanId() {
        return MDC.get(SPAN_ID);
    }

    public String getParentId() {
        return MDC.get(PARENT_ID);
    }

    public void mdc(String traceId, String spanId, String parentId) {
        if (!StringUtils.hasText(traceId)) {
            traceId = TraceIdUtil.traceId();
        }
        MDC.put(TRACE_ID, traceId);
        MDC.put(SPAN_ID, spanId);
        MDC.put(PARENT_ID, parentId);
    }

    /**
     * before
     *
     * @param traceTag 标签
     */

    protected void executeBefore(final String traceTag) {
        MDC.put(START_TIME, String.valueOf(System.currentTimeMillis()));
        if (log.isInfoEnabled()) {
            log.info(LogstashUtil.customizeMarker(LogstashUtil.kLOG_KEY_TRACE_TAG, traceTag), traceTag);
        }
    }

    /**
     * after
     *
     * @param traceTag 标签
     */
    protected void executeAfter(final String traceTag) {
        String start = MDC.get(START_TIME);
        if (StringUtils.hasText(start)) {
            long startTime = Long.parseLong(start);
            long duration = System.currentTimeMillis() - startTime;
            if (log.isInfoEnabled()) {
                log.info(LogstashUtil.customizeMarker(LogstashUtil.kLOG_KEY_TRACE_TAG, traceTag)
                        .and(append(LogstashUtil.kLOG_KEY_DURATION, duration)), traceTag);
            }
        }
    }
}
